'use strict';

/* Services */


// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('myApp.services', [])
        .factory('servicePopupFunc', ['$rootScope', '$location',
            function ($rootScope, $location) {
                return {
                    showPopupSinglePlayAgain: function () {
                        var t = this;
                        $('#popupQuitGameSingleId').off('click');
                        $('#popupQuitGameSingleId').on('click', function () {
                            t.showPopupPlayAgainClick($('#popupQuitGameSingle'));
                        });
                        $('#popupQuitGameSingle').modal('show');
                    },
                    showPopupSingleBack: function () {
                        var t = this;
                        $('#popupQuitGameSingleId').off('click');
                        $('#popupQuitGameSingleId').on('click', function () {
                            t.showPopupBackClick($('#popupQuitGameSingle'));
                        });
                        $('#popupQuitGameSingle').modal('show');
                        return $('#popupQuitGameSingle');
                    },
                    showPopupMultiPlayAgain: function () {
                        var t = this;
                        $('#popupQuitGameMultiId').off('click');
                        $('#popupQuitGameMultiId').on('click', function () {
                            t.showPopupPlayAgainClick($('#popupQuitGameMulti'));
                        });
                        $('#popupQuitGameMulti').modal('show');
                    },
                    showPopupMultiBack: function () {
                        var t = this;
                        $('#popupQuitGameMultiId').off('click');
                        $('#popupQuitGameMultiId').on('click', function () {
                            t.showPopupBackClick($('#popupQuitGameMulti'));
                        });
                        $('#popupQuitGameMulti').modal('show');
                        return $('#popupQuitGameMulti');
                    },
                    showPopupGameEnd: function (infoText, winOrLose) {
                        var t = this;

                        if (typeof infoText === 'string') {
                            $('#popupEndGameDialogInfo').text(infoText);
                        }

                        $('#popupEndGameDialog .modal-title').text('Info');
                        $('#popupEndGameDialog .modal-title').removeClass('text-danger');
                        $('#popupEndGameDialog .modal-title').removeClass('text-success');
                        if (winOrLose === true) {
                            $('#popupEndGameDialog .modal-title').text('You win !!!');
                            $('#popupEndGameDialog .modal-title').addClass('text-success');
                        }
                        if (winOrLose === false) {
                            $('#popupEndGameDialog .modal-title').text('You lose !!!');
                            $('#popupEndGameDialog .modal-title').addClass('text-danger');
                        }

                        // click ok
                        $('#popupEndGameDialogOkId').off('click');
                        $('#popupEndGameDialogOkId').on('click', function () {
                            t.showPopupPlayAgainClick($('#popupEndGameDialog'));
                        });

                        // click cancel
                        $('#popupEndGameDialogCancelId').off('click');
                        $('#popupEndGameDialogCancelId').on('click', function () {
                            t.showPopupBackClick($('#popupEndGameDialog'));
                        });

                        $('#popupEndGameDialog').modal('show');
                        return $('#popupEndGameDialog');
                    },
                    showPopupBackClick: function (popup) {
                        $location.path('/game/quit').search('url', null);
                        $rootScope.$apply();
                        popup.modal('hide');
                    },
                    showPopupPlayAgainClick: function (popup) {
                        var actualPath = $location.path();
                        $location.path('/game/quit').search('url', actualPath);
                        $rootScope.$apply();
                        popup.modal('hide');
                    }
                }
            }
        ])
        .factory('serviceMenuItem', ['$rootScope', '$location', 'servicePopupFunc',
            function ($rootScope, $location, servicePopupFunc) {
                return {
                    main: [
                        {title: 'Main menu', link: '#/main'},
                        {title: 'Settings', link: '#/main/setting'},
                        {title: 'Statistics', link: '#/main/stats'},
                        {title: 'About', link: '#/main/about'}
                    ],
                    gameSingle: [
                        {title: 'Play again', link: false, func: function () {
                                servicePopupFunc.showPopupSinglePlayAgain();
                            }},
                        {title: 'Back to menu', link: false, func: function () {
                                servicePopupFunc.showPopupSingleBack();
                            }}
                    ],
                    gameMulti: [
                        {title: 'Play again', link: false, func: function () {
                                servicePopupFunc.showPopupMultiPlayAgain();
                            }},
                        {title: 'Back to menu', link: false, func: function () {
                                servicePopupFunc.showPopupMultiBack();
                            }}
                    ],
                    gameEnd: [
                        {title: 'Play again', link: false, func: function () {
                                var actualPath = $location.path();
                                $location.path('/game/quit').search('url', actualPath);
                            }},
                        {title: 'Back to menu', link: false, func: function () {
                                $location.path('/game/quit').search('url', null);
                            }}
                    ]
                }
            }
        ])
        .factory('serviceStorage', function () {
            var storage = window.localStorage;

            if (storage.getItem('size') === null) {
                storage.setItem('size', 15);
            }
            ;

            if (storage.getItem('one') === null) {
                storage.setItem('one', 46);
            }
            ;

            if (storage.getItem('scroll') === null) {
                storage.setItem('scroll', true);
            }
            ;

            if (storage.getItem('adjust') === null) {
                storage.setItem('adjust', false);
            }
            ;

            //storage.removeItem('stats');
            if (storage.getItem('stats') === null) {
                storage.setItem('stats', angular.toJson({
                    totalMove: 0,
                    totalTime: 0,
                    totalGame: 0,
                    aiMove: 0,
                    aiTime: 0,
                    aiGame: 0,
                    aiWin: 0,
                    aiLose: 0,
                    aiDraw: 0,
                    multiMove: 0,
                    multiTime: 0,
                    multiGame: 0,
                    multiXWin: 0,
                    multiOWin: 0,
                    multiDraw: 0
                }));
            }
            ;

            storage.setItem('device', '4.1'); // or higher

            if (typeof window.device !== 'undefined') {
                // if android 2.3
                if (window.device.version.search('2.3') === 0) {
                    storage.setItem('scroll', true);
                    storage.setItem('adjust', true);
                    storage.setItem('one', 36);
                    storage.setItem('device', '2.3');
                }

                // if android 4.0
                if (window.device.version.search('4.0') === 0) {
                    storage.setItem('scroll', false);
                    storage.setItem('device', '4.0');
                }
            }

            return storage;
        })
        .factory('serviceStats', ['serviceStorage',
            function (serviceStorage) {
                return {
                    json: {},
                    load: function () {
                        var jsonString = serviceStorage.getItem('stats');
                        this.json = angular.fromJson(jsonString);
                    },
                    persist: function (serviceGame) {
                        this.load();
                        var json = this.json;
                        json.totalMove += serviceGame.movesCount;
                        json.totalTime += serviceGame.timer;
                        json.totalGame += 1;

                        if (serviceGame.singleOrMulti === 'single') {
                            json.aiMove += serviceGame.movesCount;
                            json.aiTime += serviceGame.timer;
                            json.aiGame += 1;
                            if (serviceGame.playerValue === 3) {
                                json.aiDraw += 1;
                            } else if (serviceGame.playerValue === serviceGame.winnerValue) {
                                json.aiWin += 1;
                            } else if (serviceGame.playerValue !== serviceGame.winnerValue) {
                                json.aiLose += 1;
                            }
                        }
                        if (serviceGame.singleOrMulti === 'multi') {
                            json.multiMove += serviceGame.movesCount;
                            json.multiTime += serviceGame.timer;
                            json.multiGame += 1;
                            if (serviceGame.winnerValue === 1) {
                                json.multiOWin += 1;
                            }
                            if (serviceGame.winnerValue === 2) {
                                json.multiXWin += 1;
                            }
                            if (serviceGame.winnerValue === 3) {
                                json.multiDraw += 1;
                            }
                        }

                        serviceStorage.setItem('stats', angular.toJson(json));
                    },
                    getAll: function () {
                        this.load();
                        return this.json;
                    },
                    reset: function () {
                        this.load();
                        var json = this.json;
                        for (var key in json) {
                            json[key] = 0;
                        }
                        serviceStorage.setItem('stats', angular.toJson(json));
                    }
                }
            }
        ])
        .factory('serviceGame', ['serviceStorage', '$interval',
            function (serviceStorage, $interval) {
                return {
                    singleOrMulti: 'single',
                    playerValue: 0,
                    nextMoveValue: null,
                    winnerValue: null,
                    movesCount: 0,
                    timer: 0,
                    timerPromise: null,
                    startTimer: function () {
                        var t = this;
                        t.timerPromise = $interval(function () {
                            t.timer++;
                        }, 1000);
                    },
                    stopTimer: function () {
                        if (this.timerPromise !== null) {
                            $interval.cancel(this.timerPromise);
                        }
                    },
                    getNameForValue: function (value) {
                        if (value === 1) {
                            return 'O';
                        }
                        if (value === 2) {
                            return 'X';
                        }
                        return null;
                    },
                    clear: function () {
                        this.nextMoveValue = null;
                        this.winnerValue = null;
                        this.singleOrMulti = 'single';
                        this.playerValue = 0;
                        this.movesCount = 0;
                        this.timer = 0;
                        this.stopTimer();
                    },
                    createGameFromStorage: function () {

                        var one = parseInt(serviceStorage.getItem('one'));

                        var game = new Tictactoe(
                                'tictactoeCanvas',
                                'tictactoeContainer',
                                {
                                    size: serviceStorage.getItem('size'),
                                    scroll: (serviceStorage.getItem('scroll') == 'true'),
                                    one: {
                                        w: one,
                                        h: one
                                    }
                                }
                        );

                        if ((serviceStorage.getItem('adjust') == 'true')) {
                            game.autoAdjust();
                        }

                        return game;
                    }
                }
            }
        ]);

